import React, { useEffect, useMemo, useRef, useState } from 'react';
// 引入 echarts 核心模块，核心模块提供了 echarts 使用必须要的接口。
import * as echarts from 'echarts/core';
// 引入柱状图图表，图表后缀都为 Chart
import {
    PieChart
} from 'echarts/charts';
// 引入提示框，标题，直角坐标系组件，组件后缀都为 Component
import {
    ToolboxComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent,
    TitleComponent
} from 'echarts/components';
// 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import {
    CanvasRenderer
} from 'echarts/renderers';
import Base from './base';

// 注册必须的组件
echarts.use(
    [
        ToolboxComponent,
        TooltipComponent,
        GridComponent,
        LegendComponent,
        PieChart,
        TitleComponent,
        CanvasRenderer
    ]
);

const setEcharts = (obj, property, ele, dataList) => {
    const option = {
        title: {
            text: property.title,
            left: 'center',
            textStyle: {
                fontSize: 32,
            }
        },
        tooltip: {
            trigger: 'item'
        },
        textStyle: {
            fontSize: 28,
        },
        legend: {
            orient: 'vertical',
            left: 'left'
        },
        series: [
            {
                name: property.pieName,
                type: 'pie',
                radius: '50%',
                data: dataList,
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };

    if (obj.chart) obj.chart.dispose();
    obj.chart = echarts.init(ele);
    obj.chart.setOption(option);
};

export default React.memo((props) => {
    const { property } = Base.getProps(props);
    const [isVisible, setIsVisible] = useState(property.isVisible !== false);
    const [dataList, setDataList] = useState(property.dataList || []);
    const obj = useMemo(() => ({}), []);

    const div = useRef(null);

    useEffect(() => {
        if (div.current) {
            setEcharts(obj, property, div.current, dataList);
        }
    }, [obj, div, dataList, property]);

    property.setVisible = (v) => setIsVisible(v);
    property.setDataList = (d) => setDataList(d);
    property.setRefresh = () => setEcharts(obj, property, div.current, dataList);

    if (!isVisible) return null;

    return <div className={property.className} style={property.style}>
        <div style={{ height: '100%' }} ref={div}></div>
    </div>;
});